package com.inossem.allotin.activity.bluetooth;

import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;

import com.inossem.allotin.receiver.GattUpdateReceiver;
import com.inossem.allotin.service.BluetoothLeService;
import com.inossem.allotin.utils.ACacheUtils;

import java.util.List;

/**
 * @author 王斯宇
 * @time on 2019/7/8 14:49
 * @email siyu.wang@inossem.com
 */
public abstract class BlueToothBaseActivity extends AppCompatActivity {
    private final static String TAG = BlueToothBaseActivity.class
            .getSimpleName();
    private BluetoothLeService mBluetoothLeService;
    private String mDeviceAddress;
    private String mDeviceName;
    private OnBluetoothResuleListener listener;
    private boolean isBluetooth = false;
    private GattUpdateReceiver mGattUpdateReceiver;
    private static final String[] READ_ARRAY = {"0000fff6-0000-1000-8000-00805f9b34fb" , "0000fff4-0000-1000-8000-00805f9b34fb" , "00002aa1-0000-1000-8000-00805f9b34fb"};

    // Code to manage Service lifecycle.
    /**
     * Activity绑定service需要
     */
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName,
                                       IBinder service) {
            //获取到服务
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service)
                    .getService();
            com.orhanobut.logger.Logger.i("service连接成功");
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up
            // initialization.
            if (!TextUtils.isEmpty(mDeviceAddress)){
                mBluetoothLeService.connect(mDeviceAddress);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    /**
     * 注册广播
     */
    private void registerReceiver() {
        mGattUpdateReceiver = new GattUpdateReceiver(new GattUpdateReceiver.ScanListener() {
            //扫描结果回调
            @Override
            public void onResult(String scanResult) {
                listener.OnResuktListener(scanResult);
            }
            //获取到当前设备支持的操作
            @Override
            public void onGattServicesListener() {
                ACacheUtils.setBluetoothAddress(TextUtils.isEmpty(mDeviceAddress) ? "" :mDeviceAddress);
                ACacheUtils.setBluetoothName(TextUtils.isEmpty(mDeviceName) ? "" :mDeviceName);
                //判断设备是否支持从设备读数据
                displayGattServices(mBluetoothLeService
                        .getSupportedGattServices());
            }
        });
        //注册广播
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    }

    /**
     * 连接蓝牙设备并设置扫描结果监听
     * @param address 蓝牙设备mac地址
     * @param name  蓝牙设备名称
     * @param listener  结果回调
     */
    public void setBuletoothScan(String address ,String name , OnBluetoothResuleListener listener){
        this.listener = listener;
        isBluetooth = true;
        bindService();
        registerReceiver();
        if (!TextUtils.isEmpty(address)){
            mDeviceAddress = address;
            mDeviceName = name;
            if (mBluetoothLeService != null) {
                //连接蓝牙
                final boolean result = mBluetoothLeService.connect(mDeviceAddress);
                com.orhanobut.logger.Logger.i("Connect request result=" + result);
            }
        }
    }

    /**
     * 绑定服务
     * @return
     */
    private boolean bindService (){
        //绑定服务
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        boolean bll = bindService(gattServiceIntent, mServiceConnection,
                BIND_AUTO_CREATE);
        return bll;
    }
    /**
     * 设置扫描结果监听
     * @param listener  结果回调
     */
    public void setBuletoothScan(OnBluetoothResuleListener listener){
       setBuletoothScan("" , "" ,listener);
    }

    /**
     * 判断设备是否支持从设备读数据
     * @param gattServices  设备所支持的行为的list
     */
    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null){
            return;
        }
        for (BluetoothGattService service : gattServices){
            for (BluetoothGattCharacteristic characteristic : service.getCharacteristics()){
                final int charaProp = characteristic.getProperties();
                if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                    for (int i = 0; i < READ_ARRAY.length; i++) {
                        if (characteristic.getUuid().toString().equals(READ_ARRAY[i])) {
                            System.out.println("enable notification");
                            //开启从设备读数据
                            mBluetoothLeService.setCharacteristicNotification(
                                    characteristic, true);
                            break;
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取指定mac地址的设备的连接状态
     * @param mDeviceAddress 设备的mac地址
     * @return true 已连接 false 未连接
     */
    public boolean getConnectStatus (String mDeviceAddress){
        bindService();
        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
            return result;
        }
        return false;
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (isBluetooth){
            registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
            if (mBluetoothLeService != null) {
                final boolean result = mBluetoothLeService.connect(mDeviceAddress);
                com.orhanobut.logger.Logger.i("Connect request result=" + result);
            }
        }

    }
    @Override
    protected void onPause() {
        super.onPause();
        if (isBluetooth) {
            unregisterReceiver(mGattUpdateReceiver);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBluetooth) {
            unbindService(mServiceConnection);
            mBluetoothLeService = null;
        }
    }

    /**
     * 广播过滤器
     * @return
     */
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter
                .addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    public interface OnBluetoothResuleListener {
        void OnResuktListener(String result);
    }
}
